import { NextRequest, NextResponse } from "next/server"
import * as fs from "fs"
import * as path from "path"

export const dynamic = "force-dynamic"

export interface ModelProvider {
  id: string
  name: string
  apiKey: string
  baseUrl: string
  enabled: boolean
}

const ENV_FILE_PATH = path.join(process.cwd(), ".env")

// 读取 .env 文件并解析模型配置
function readModelProviders(): ModelProvider[] {
  try {
    if (!fs.existsSync(ENV_FILE_PATH)) {
      return []
    }

    const content = fs.readFileSync(ENV_FILE_PATH, "utf-8")
    const lines = content.split("\n")
    const providers: Map<string, Partial<ModelProvider>> = new Map()

    lines.forEach((line) => {
      const trimmed = line.trim()
      if (!trimmed || trimmed.startsWith("#")) return

      // 匹配格式：PROVIDER_ID_KEY=value
      const match = trimmed.match(/^([A-Z][A-Z0-9_]*?)_(NAME|API_KEY|APIKEY|BASE_URL|BASEURL|ENABLED)=(.*)$/)
      if (!match) return

      const [, providerId, key, value] = match
      if (!providers.has(providerId)) {
        providers.set(providerId, { id: providerId })
      }

      const provider = providers.get(providerId)!
      if (key === "API_KEY" || key === "APIKEY") {
        provider.apiKey = value
      } else if (key === "BASE_URL" || key === "BASEURL") {
        provider.baseUrl = value
      } else if (key === "NAME") {
        provider.name = value
      } else if (key === "ENABLED") {
        provider.enabled = value === "true"
      }
    })

    return Array.from(providers.values())
      .filter((p) => p.apiKey) // 只返回有 API Key 的配置
      .map((p) => ({
        id: p.id!,
        name: p.name || formatProviderName(p.id!),
        apiKey: p.apiKey!,
        baseUrl: p.baseUrl || "",
        enabled: p.enabled ?? true,
      }))
  } catch (error) {
    console.error("Error reading .env file:", error)
    return []
  }
}

// 将配置写入 .env 文件
function writeModelProviders(providers: ModelProvider[]): void {
  try {
    // 读取现有的 .env 文件，保留其他配置
    let existingContent = ""
    if (fs.existsSync(ENV_FILE_PATH)) {
      existingContent = fs.readFileSync(ENV_FILE_PATH, "utf-8")
    }

    // 移除所有模型配置相关的行
    const lines = existingContent.split("\n")
    const providerIds = providers.map((p) => p.id)
    const otherLines = lines.filter((line) => {
      const trimmed = line.trim()
      if (!trimmed || trimmed.startsWith("#")) return true

      // 检查是否是模型配置行
      const match = trimmed.match(/^([A-Z_]+)_/)
      if (!match) return true

      const providerId = match[1]
      return !providerIds.includes(providerId)
    })

    // 构建新的配置内容
    const newLines: string[] = []

    // 保留其他配置
    if (otherLines.length > 0 && otherLines.some(l => l.trim())) {
      newLines.push(...otherLines)
      newLines.push("") // 添加空行分隔
    }

    // 添加模型配置
    newLines.push("# Model Provider Configurations")
    providers.forEach((provider) => {
      newLines.push("")
      newLines.push(`# ${provider.name}`)
      newLines.push(`${provider.id}_NAME=${provider.name}`)
      newLines.push(`${provider.id}_API_KEY=${provider.apiKey}`)
      if (provider.baseUrl) {
        newLines.push(`${provider.id}_BASE_URL=${provider.baseUrl}`)
      }
      newLines.push(`${provider.id}_ENABLED=${provider.enabled}`)
    })

    const newContent = newLines.join("\n") + "\n"
    fs.writeFileSync(ENV_FILE_PATH, newContent, "utf-8")
  } catch (error) {
    console.error("Error writing .env file:", error)
    throw error
  }
}

// 格式化供应商名称
function formatProviderName(id: string): string {
  const nameMap: Record<string, string> = {
    OPENAI: "OpenAI",
    ANTHROPIC: "Anthropic Claude",
    GOOGLE: "Google Gemini",
    AZURE: "Azure OpenAI",
    QWEN: "阿里通义千问",
    GLM: "智谱 ChatGLM",
    ERNIE: "百度文心一言",
    DEEPSEEK: "DeepSeek",
    MOONSHOT: "月之暗面 Kimi",
  }
  return nameMap[id] || id
}

// GET - 读取所有模型配置
export async function GET() {
  try {
    const providers = readModelProviders()

    // 出于安全考虑，在返回给前端时，隐藏部分 API Key
    const sanitizedProviders = providers.map((p) => ({
      ...p,
      apiKey: maskApiKey(p.apiKey),
    }))

    return NextResponse.json({
      success: true,
      data: sanitizedProviders,
    })
  } catch (error) {
    console.error("Error reading model providers:", error)
    return NextResponse.json(
      { success: false, error: "Failed to read model providers" },
      { status: 500 },
    )
  }
}

// POST - 保存模型配置
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { providers } = body as { providers: ModelProvider[] }

    if (!Array.isArray(providers)) {
      return NextResponse.json({ success: false, error: "Invalid providers data" }, { status: 400 })
    }

    // 验证数据
    for (const provider of providers) {
      if (!provider.id || !provider.name || !provider.apiKey) {
        return NextResponse.json(
          { success: false, error: "Each provider must have id, name, and apiKey" },
          { status: 400 },
        )
      }
    }

    writeModelProviders(providers)

    return NextResponse.json({
      success: true,
      message: "Model providers saved successfully",
    })
  } catch (error) {
    console.error("Error saving model providers:", error)
    return NextResponse.json({ success: false, error: "Failed to save model providers" }, { status: 500 })
  }
}

// 辅助函数：隐藏 API Key 的部分字符
function maskApiKey(apiKey: string): string {
  if (!apiKey) return ""
  if (apiKey.length <= 8) return "****"
  return apiKey.substring(0, 6) + "****" + apiKey.substring(apiKey.length - 4)
}
